package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Borrow_books_Activity extends AppCompatActivity {
    private ImageView imgBack;
    private EditText etBookTitle, etReaderName;
    private Button btnSubmit;

    private BookDatabaseHelper bookDbHelper;
    private ReaderDatabaseHelper readerDbHelper;
    private BorrowDatabaseHelper borrowDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_borrow_books);

        // 初始化视图
        imgBack = findViewById(R.id.btn_back);
        etBookTitle = findViewById(R.id.et_book_id);
        etReaderName = findViewById(R.id.et_reader_id);
        btnSubmit = findViewById(R.id.btn_submit);

        // 初始化数据库帮助类
        bookDbHelper = new BookDatabaseHelper(this);
        readerDbHelper = new ReaderDatabaseHelper(this);
        borrowDbHelper = new BorrowDatabaseHelper(this);

        // 返回按钮点击事件
        imgBack.setOnClickListener(v -> finish());

        // 提交按钮点击事件
        btnSubmit.setOnClickListener(v -> {
            String bookTitle = etBookTitle.getText().toString().trim();
            String readerName = etReaderName.getText().toString().trim();

            if (bookTitle.isEmpty() || readerName.isEmpty()) {
                Toast.makeText(this, "请输入书名和读者姓名", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查书籍是否存在
            if (!bookDbHelper.isBookAvailable(bookTitle)) {
                Toast.makeText(this, "书籍不存在", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查读者是否存在
            if (!readerDbHelper.isReaderAvailable(readerName)) {
                Toast.makeText(this, "读者不存在", Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取书籍ID和读者ID
            int bookId = bookDbHelper.getBookIdByTitle(bookTitle);
            int readerId = readerDbHelper.getReaderIdByName(readerName);

            // 获取当前日期作为借阅日期
            String borrowDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

            // 添加借阅记录
            boolean success = borrowDbHelper.addBorrowRecord(bookId, readerId, borrowDate);

            if (success) {
                Toast.makeText(this, "借阅成功", Toast.LENGTH_SHORT).show();
                etBookTitle.setText("");
                etReaderName.setText("");
            } else {
                Toast.makeText(this, "借阅失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }
}